package org.xqh.study.mq.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.xqh.utils.DateUtil;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName RabbitMQProducer
 * @Description TODO
 * @Author xuqianghui
 * @Date 2022/10/13 14:34
 * @Version 1.0
 */
@Slf4j
public class RabbitMQProducer {

    public static Channel channel;


    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection c = RabbitMQConfig.initConnectionFactory().newConnection();
        channel = c.createChannel();
        channel.exchangeDeclare(RabbitMQConfig.exchange, BuiltinExchangeType.DIRECT, true);
        // 声明持久化、排他的、非自动删除的队列 (这里 声明队列 )
//        channel.queueDeclare(RabbitMQConfig.queueName, true, true, false, new HashMap<>());
        // 声明持久化、非自动删除、绑定类型为 direct 的交换器
        channel.queueBind(RabbitMQConfig.queueName, RabbitMQConfig.exchange, RabbitMQConfig.routeKey);
        for(int i = 0; i < 10; i ++ ){
            String str = String.format("a msg with time %s", DateUtil.formatDate(new Date(), DateUtil.DATE_PATTERN_COMPLEX_MILLI));
            MQMsg msg = new MQMsg();
            msg.setMsg(str);
            String jsonMsg = JSON.toJSONString(msg);
            System.out.println(String.format("send msg: {%s}", jsonMsg));
            pushMsg(jsonMsg);
            Thread.sleep(10);
        }
        channel.close();
        c.close();
    }

    @Data
    public static class MQMsg{
        private String msg;
    }

    public static void pushMsg(String msg) throws IOException {
        if(StringUtils.hasText(msg)){
            channel.basicPublish(RabbitMQConfig.exchange, RabbitMQConfig.routeKey, RabbitMQConfig.getBasicProperties(), msg.getBytes("UTF-8"));
        }
    }




}
